<template>
  <div>
    <div v-if="isShow">
      <!-- 条件查询申领表单 -->
      <div class="check-form-box">
        <el-form
          :inline="true"
          :model="searchModel.data"
          class="demo-form-inline"
        >
          <el-form-item label="创建日期">
            <el-date-picker
              v-model="searchModel.createDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item label="申请人">
            <el-input
              v-model.trim="searchModel.applyUser"
              placeholder="请输入申请人"
            />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select
              v-model="searchModel.frontStateCode"
              placeholder="请选择"
            >
              <el-option label="全部" :value="null" />
              <el-option label="待上传凭证" value="1" />
              <el-option label="待审核" value="2" />
              <el-option label="审核不通过" value="3" />
              <el-option label="待发货" value="4" />
              <el-option label="已发货" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" color="#ea5b24" @click="searchOrder()"
              >查询</el-button
            >
            <el-button
              type="primary"
              color="#ea5b24"
              @click="exportOrder()"
              v-if="pinia.isShow[118]"
              >导出Excel</el-button
            >
            <!-- <el-button type="primary" color="#ea5b24" @click="exportOrder()"
              >导出发货明细</el-button
            > -->
            <!-- <el-upload
              class="upload"
              action=""
              :multiple="false"
              :show-file-list="false"
              accept=".xls"
              :http-request="httpRequest"
            >
              <el-button type="primary" color="#ea5b24">导入发货明细</el-button>
            </el-upload> -->
          </el-form-item>
        </el-form>
      </div>

      <!-- 申领订单列表 -->
      <div>
        <el-table :data="tableData.data" style="width: 100%">
          <el-table-column prop="createTime" label="创建日期" />
          <el-table-column prop="orderNo" label="订单号" />
          <el-table-column prop="applyUserId" label="申请人id" />
          <el-table-column prop="applyUserName" label="申请人" />
          <el-table-column prop="goodsName" label="商品" />
          <el-table-column prop="supplyNum" label="申请数量" />
          <el-table-column label="押金金额">
            <template #default="scope">
              <div
                :style="{
                  color: scope.row.paymentVoucherUrl ? '#169BD5' : 'black',
                }"
              >
                <span @click="showImg(scope.row.paymentVoucherUrl)">{{
                  scope.row.price
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单状态">
            <template #default="scope">
              <div
                @click="showReason(scope.row)"
                :style="{ color: judgeStateColor(scope.row) }"
              >
                {{ scope.row.frontStateStr }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot:default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="examineDialog(scope.row)"
                v-if="
                  pinia.isShow[120] &&
                  scope.row.paymentVoucherUrl &&
                  scope.row.frontStateCode == 2
                "
              >
                {{ "凭证审核" }}
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="showDetails(scope.row)"
                v-if="pinia.isShow[119]"
              >
                {{ "详情" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页插件 -->
        <div style="text-align: center">
          <el-pagination
            :total="totalNum"
            @current-change="handleCurrentChange"
            background
            :page-size="size"
            layout="prev, pager, next, total"
            :current-page="page"
          />
        </div>
      </div>

      <!-- 审核dialog -->
      <el-dialog
        v-model="examineDialogVisible"
        title="凭证审核"
        center="true"
        modal="true"
        width="450px"
      >
        <el-form :model="examineParam">
          <el-form-item label="审核:">
            <el-radio-group
              v-model="examineParam.checkState"
              @change="resultChange"
            >
              <el-radio :label="1">审核通过</el-radio>
              <el-radio :label="2">审核不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="不通过原因">
            <el-input
              v-model.trim="examineParam.note"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :disabled="isNote"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="examineDialogVisible = false">取消</el-button>
            <el-button type="primary" color="#ea5b24" @click="examineReview()"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
      <!-- 图片展示dialog -->
      <el-dialog
        v-model="imgDialog"
        width="500px"
        draggable
        center
        :show-close="false"
      >
        <div v-if="imgDialog">
          <el-image :src="imgSrc" :preview-src-list="srcList" />
        </div>
      </el-dialog>
      <!-- 审核不通过原因 -->
      <el-dialog title="审核不通过原因" v-model="dialogVisible" width="30%">
        <span>{{ reason }}</span>
      </el-dialog>
    </div>
    <div v-else>
      <detaild
        :detaildData="detaildData"
        @packConfigBack="showDetails"
      ></detaild>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import detaild from "./detaild.vue";
import * as XLSX from "xlsx";
import { formatDateTime } from "../../../utils/formatDateTime";
import {
  findSupplyOrderApi,
  examineSupplyOrderApi,
  findSupplyExcelApi,
} from "../../../api/index";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 控制详情组件显示
const isShow = ref(true);
// 传入详情组件参数
const detaildData = ref({
  orderId: null,
});

// 审核dialog控制
const examineDialogVisible = ref(false);
// 审核不通过原因输入框状态
const isNote = ref(true);
// 审核参数
const examineParam = reactive({
  orderId: null,
  checkState: null,
  note: null,
});

// 控制审核失败原因显示
const dialogVisible = ref(false);
// 审核不通过原因
const reason = ref("");

// 照片dialog控制
const imgDialog = ref(false);
let imgSrc = ref("");
let srcList = reactive([]);

// 判断订单状态显示文字
const judgeFrontStateCode = (row) => {
  switch (row.frontStateCode) {
    case 1:
      return "待上传凭证";
    case 2:
      return "待审核";
    case 3:
      return "审核不通过";
    case 4:
      return "待发货";
    case 5:
      return "已发货";
    default:
      return "";
  }
};

// 判断订单状态颜色
const judgeStateColor = (row) => {
  switch (row.frontStateCode) {
    case 3:
      return "#F98A09";
    case 5:
      return "#21D86E";
    default:
      return "black";
  }
};

// 翻页
let flipData = reactive({
  pageNum: page,
  pageSize: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.pageNum = page.value;
  findOrder(flipData);
};

// 搜索模型
const searchModel: any = reactive({
  createDate: null,
  startTime: null,
  endTime: null,
  applyUser: null,
  frontStateCode: null,
  pageNum: page,
  pageSize: size,
});

// 打开审核dialog
const examineDialog = (row) => {
  Object.keys(examineParam).forEach((key) => (examineParam[key] = null));
  examineDialogVisible.value = true;
  examineParam.orderId = row.orderNo;
};

// 展示审核不通过原因
const showReason = (item) => {
  if (item.frontStateCode === 3) {
    reason.value = item.note;
    dialogVisible.value = true;
  }
};

// 展示详情
const showDetails = (item = null) => {
  if (item) {
    detaildData.value.orderId = item.orderNo;
  } else {
    findOrder(searchModel);
  }
  isShow.value = !isShow.value;
};

// 展示押金图片
const showImg = (src) => {
  if (src) {
    imgDialog.value = true;
    imgSrc.value = src;
    srcList.length = 0;
    srcList.push(imgSrc.value);
  }
};

const resultChange = (val) => {
  switch (val) {
    case 1:
      isNote.value = true;
      examineParam.note = null;
      break;
    case 2:
      isNote.value = false;
      break;
  }
};

// 搜索退款详情
const searchOrder = () => {
  page.value = 1;
  if (searchModel.createDate) {
    searchModel.startTime = formatDateTime(searchModel.createDate[0]);
    searchModel.endTime = formatDateTime(searchModel.createDate[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.startTime = null;
    searchModel.endTime = null;
  }
  searchParmSearch();
  findOrder(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};
// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

// 查询申领订单
const findOrder = (searchModel) => {
  findSupplyOrderApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.items;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 审核
const examineReview = () => {
  if (examineParam.checkState == null) {
    ElMessage.warning("请选择审核状态.");
    return;
  }
  if (
    examineParam.checkState == 2 &&
    (examineParam.note == "" || examineParam.note == null)
  ) {
    ElMessage.warning("请输入不通过原因.");
  } else {
    examineSupplyOrderApi(examineParam).then((res) => {
      if (res.data.code === 2000) {
        ElMessage({
          message: "审核成功.",
          type: "success",
        });
      } else {
        switch (res.data.code) {
          case 4001:
            ElMessage.error("审核结果状态错误.");
            break;
          case 4002:
            ElMessage.error("审核不通过, 必须输入原因.");
            break;
          default:
            ElMessage.error("审核失败.");
            break;
        }
      }
      examineDialogVisible.value = false;
      findOrder(searchModel);
    });
  }
};

//导出订单
const exportOrder = () => {
  findSupplyExcelApi(searchModel).then((res) => {
    const blob = new Blob([res.data]);
    const fileName = "申领订单数据.xls";
    const elink = document.createElement("a"); // 创建a标签
    elink.download = fileName; // 为a标签添加download属性
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click(); // 点击下载
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink); // 释放标签
  });
};

// 导入订单
const httpRequest = (e) => {
  let file = e.file; // 文件信息
  if (!file) {
    // 没有文件
    return false;
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    ElMessage.error("上传格式不正确，请上传xls或者xlsx格式.");
    return false;
  }

  const fileReader = new FileReader();
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result;
      const workbook = XLSX.read(data, {
        type: "binary", // 以字符编码的方式解析
      });
      const exlname = workbook.SheetNames[0]; // 取第一张表
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]); //生成json表格内容
      console.log("excel:" + JSON.stringify(exl));

      //   将 JSON 数据挂到 data 里
      //   this.tableData = exl;
      // document.getElementsByName('file')[0].value = ''
      // 根据自己需求，可重置上传value为空，允许重复上传同一文件
    } catch (e) {
      ElMessage.error("导入失败：系统错误.");
      return false;
    }
  };
  fileReader.readAsBinaryString(file);
};

onMounted(() => {
  findOrder(searchModel);
});
</script>
<style scoped></style>
